﻿using System;
using System.Diagnostics;
using System.Net;
using System.Text;
using SvnDeploy.Service.Cfg;

namespace SvnDeploy.Service.Impl
{
    internal class DeploymentWorkerImpl : IDeploymentWorker
    {
        private readonly SvnDeployConfigurationSection configuration;
        private readonly ILog log;
        private StringBuilder logMessage;        

        public DeploymentWorkerImpl(IVirtualDirectoryUpdater virtualDirectoryUpdater, ILog log, SvnDeployConfigurationSection configuration)
        {
            VirtualDirectoryUpdater = virtualDirectoryUpdater;
            this.configuration = configuration;
            this.log = log;
            SetSvnAuthentication();
        }

        public IVirtualDirectoryUpdater VirtualDirectoryUpdater { get; private set; }

        public void Deploy()
        {
            ClearLogMessage();
            foreach (ApplicationElement application in configuration.Applications)
            {
                AppendToLog(string.Format("Deploying application: {0}, SVN Path: {1}, Directory: {2}", application.Name, application.SvnPath, application.VirtualDirectory));
                try
                {
                    VirtualDirectoryUpdater.CheckOutOrUpdate(application.Name, application.SvnPath, application.VirtualDirectory);
                    AppendToLog(VirtualDirectoryUpdater.WasUpdated ? "Updated to revision " + VirtualDirectoryUpdater.Revision : "No changes detected. Directory revision " + VirtualDirectoryUpdater.Revision);
                }
                catch (Exception ex)
                {
                    log.Write(ex.Message, EventLogEntryType.Error);
                }
            }
            log.Write(logMessage.ToString(), EventLogEntryType.Information);
        }

        private void AppendToLog(string message)
        {
            logMessage.AppendLine(message);
        }

        private void ClearLogMessage()
        {
            logMessage = new StringBuilder();
        }

        private void SetSvnAuthentication()
        {
            if (configuration.Authentication != null)
            {
                var domain = configuration.Authentication.Domain;
                var username = configuration.Authentication.Username;
                var password = configuration.Authentication.Password;
                var credentials = new NetworkCredential(username, password, domain);
                VirtualDirectoryUpdater.SetAuthentication(credentials);
            }
        }
    }
}
